package Demo;

class MyBlockingQueue{
    private String[] data=null;
    private volatile int size=0;
    private volatile int head=0;
    private volatile int tail=0;
    private Object blocker=new Object();
    public MyBlockingQueue(int capacity){
        data=new String[capacity];
    }
    public void put(String s) throws InterruptedException {
        synchronized (blocker){
            while(size==data.length){
                blocker.wait();
            }
            data[tail]=s;
            tail++;
            if(tail>=data.length){
                tail=0;
            }
            size++;
            blocker.notify();
        }
    }
    public String take() throws InterruptedException {
        synchronized (blocker){
            while(size==0){
                blocker.wait();
            }
            String m=data[head];
            head++;
            if(head>=data.length){
                head=0;
            }
            size--;
            blocker.notify();
            return m;
        }
    }
}
public class Text {
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue=new MyBlockingQueue(100);
        Thread producter=new Thread(()->{
            int n=0;
            while(true){
                    try {
                        myBlockingQueue.put(String.valueOf(n));
                        System.out.println("生产："+n);
                        n++;
                        //Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            }
        },"producter");
        Thread consumer=new Thread(()->{
            while(true){
                    try {
                       String s=myBlockingQueue.take();
                        System.out.println("消费："+s);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            }
        },"consumer");
        producter.start();
        consumer.start();
    }
    /*public static int count=5;
    public synchronized static int buyTicket(){
        if (count<=0) return -1;
        count--;
        System.out.println("剩余票数:"+count);
        return count;
    }
    public static void main1(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(){
                public void run(){
                    Text.buyTicket();
                }
            }.start();
        }
    }*/
}
